package com.atguigu.day08;

import com.atguigu.bean.WaterSensor;
import org.apache.commons.compress.utils.Lists;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;

public class Flink05_State_KeyedState_ListState {

    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.读取数据
        DataStreamSource<String> socketTextStream = env.socketTextStream("hadoop102", 9999);

        //3.将每行数据转换为JavaBean
        SingleOutputStreamOperator<WaterSensor> waterSensorDS = socketTextStream.map(line -> {
            String[] fields = line.split(",");
            return new WaterSensor(fields[0],
                    Long.parseLong(fields[1]),
                    Double.parseDouble(fields[2]));

        });

        //4.按照传感器Id分组
        KeyedStream<WaterSensor, String> keyedStream = waterSensorDS.keyBy(WaterSensor::getId);

        //5.使用状态编程实现输出每个传感器最高的三个水位线的数据
        SingleOutputStreamOperator<WaterSensor> topNWaterSensorDS = keyedStream.flatMap(new MyRichMapTopNFunc(3));

        //6.打印
        topNWaterSensorDS.print();

        //7.启动
        env.execute();

    }

    public static class MyRichMapTopNFunc extends RichFlatMapFunction<WaterSensor, WaterSensor> {

        //定义属性,用于表示展示TopN
        private int topSize;

        //定义集合状态用于存放历史数据
        private ListState<WaterSensor> listState;

        public MyRichMapTopNFunc(Integer topSize) {
            this.topSize = topSize;
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            listState = getRuntimeContext().getListState(new ListStateDescriptor<WaterSensor>("list-state", WaterSensor.class));
        }

        @Override
        public void flatMap(WaterSensor value, Collector<WaterSensor> out) throws Exception {

            //将当前数据存入状态
            listState.add(value);

            //取出状态中所有的数据
            Iterator<WaterSensor> iterator = listState.get().iterator();
            ArrayList<WaterSensor> waterSensors = Lists.newArrayList(iterator);

            //排序
            waterSensors.sort(new Comparator<WaterSensor>() {
                @Override
                public int compare(WaterSensor o1, WaterSensor o2) {
//                    if (o1.getVc() > o2.getVc()) {
//                        return -1;
//                    } else if (o1.getVc() < o2.getVc()) {
//                        return 1;
//                    } else {
//                        return 0;
//                    }
                    return o2.getVc().compareTo(o1.getVc());

//                    if (o1.getVc() > o2.getVc()) {
//                        return 1;
//                    } else if (o1.getVc() < o2.getVc()) {
//                        return -1;
//                    } else {
//                        return 0;
//                    }
//                    return o1.getVc().compareTo(o2.getVc());

                }
            });

            //输出 : 保存所有历史数据
//            for (int i = 0; i < Math.min(topSize, waterSensors.size()); i++) {
//                out.collect(waterSensors.get(i));
//            }

            //输出：只保留TopSize的数据
            if (waterSensors.size() > topSize) {
                waterSensors.remove(topSize);
                //更新至状态
                listState.update(waterSensors);
            }
            for (WaterSensor waterSensor : waterSensors) {
                out.collect(waterSensor);
            }
        }
    }

}
